package com.ruoyi.web.controller.app;

import com.ruoyi.business.domain.TOrder;
import com.ruoyi.business.service.ITOrderService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * B端 订单管理接口
 */
@RestController
@RequestMapping("/b-api/order")
public class BapiOrderController extends BaseController {

    @Autowired
    private ITOrderService orderService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    /**
     * 获取订单列表 (合作商/经销商通用)
     */
    @GetMapping("/list")
    public TableDataInfo list(TOrder order) {
        // 数据权限将通过 @DataScope 自动处理
        startPage();
        List<TOrder> list = orderService.selectOrderListWithItems(order);
        return getDataTable(list);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{orderId}")
    public AjaxResult getDetail(@PathVariable("orderId") Long orderId) {
        TOrder order = orderService.selectOrderDetailById(orderId);

        // 安全校验：确保用户只能查看权限范围内的订单
        if (order == null) {
            return AjaxResult.error("订单不存在");
        }

        // 这里需要一段手动的数据权限校验逻辑，因为@DataScope无法作用于单条查询
        boolean hasPermission = checkOrderPermission(order);
        if (!hasPermission) {
            return AjaxResult.error("订单不存在或无权访问");
        }

        return AjaxResult.success(order);
    }

    /**
     * 检查当前登录的B端用户是否有权限查看此订单
     * @param order 订单对象
     * @return 是否有权限
     */
    private boolean checkOrderPermission(TOrder order) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long currentUserId = loginUser.getUserId();
        SysUser user = userService.selectUserByUserName(SecurityUtils.getUsername());
        Set<String> roles = permissionService.getRolePermission(user);

        if (roles.contains("partner")) {
            // 合作商：订单关联的设备，其partner_id必须是自己
            // 这个校验需要查询设备信息，我们可以在Service层完成
            return orderService.checkPartnerOrderPermission(currentUserId, order.getOrderId());
        } else if (roles.contains("distributor")) {
            // 经销商：订单关联的设备，其distributor_id必须是自己
            return orderService.checkDistributorOrderPermission(currentUserId, order.getOrderId());
        }
        return false;
    }
}